<?php

namespace app\service\admin;

use app\service\base\BaseLogic;

class AdminRoleLogic extends BaseLogic
{
    const SUPER = 1;

    public function getList($name, $limit)
    {
        $arrWhere = [];
        $name && $arrWhere[] = ['name', 'like', "%{$name}%"];
        return (new AdminRoleModel())->getPage($arrWhere, $limit);
    }

    public function getAll()
    {
        return (new AdminRoleModel())->getAll();
    }

    public function check($name)
    {
        $arrWhere = [];
        $arrWhere['name'] = $name;
        return (new AdminRoleModel())->getRow($arrWhere);
    }

    public function add($name, $desc)
    {
        $arrWhere = [];
        $arrWhere['name'] = $name;
        $oModel = new AdminRoleModel();
        $exist = $oModel->getRow($arrWhere);
        if ($exist) {
            throw new \Exception('已存在相同名称');
        }

        return $oModel->add($name, $desc);
    }

    public function edit($id, $name, $desc)
    {
        $arrWhere = [];
        $arrWhere[] = ['id', '<>', $id];
        $arrWhere[] = ['name', '=', $name];
        $exist = (new AdminRoleModel())->getRow($arrWhere);
        if ($exist) {
            throw new \Exception('已存在相同名称');
        }

        return (new AdminRoleModel())->edit($id, $name, $desc);
    }

    public function getRowById($id)
    {
        $arrWhere = [];
        $arrWhere['id'] = $id;
        return (new AdminRoleModel())->getRow($arrWhere);
    }

    public function del($id)
    {
        if (empty($id)) {
            throw new \Exception('更新参数错误');
        }
        return (new AdminRoleModel())->delById($id);
    }

    public function getMenuList($roleId)
    {
        if ($roleId == self::SUPER) {
            return AdminPurviewLogic::getInstance()->treeList();
        } else {
            $arrPurviewId = RolePurviewLogic::getInstance()->getListByRoleId($roleId);
            if (empty($arrPurviewId)) {
                return [];
            }
            $arrPurviewId = array_column($arrPurviewId, 'admin_purview_id');
            return AdminPurviewLogic::getInstance()->treeListByIds($arrPurviewId);
        }
    }
}